// Package web
// Created by GoLand
// @User: lenora
// @Date: 2023/12/16
// @Time: 15:54

package ginx

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type ApiResponse struct {
	Code    int16  `json:"code"`    // 状态码
	Message string `json:"message"` // 状态短语
	Result  any    `json:"result"`  // 数据结果集
}

const (
	SUCCESS int16 = 0
	FAIL    int16 = 4000

	ACCESS_DENY int16 = 2003
	NOT_SUPPORT int16 = 2004

	NOT_FOUND     int16 = 3001
	ALREADY_EXIST int16 = 3002

	WRONG_PARAM int16 = 4001
)

var WrongMessage = map[int16]string{
	0: "请求成功",

	3001: "记录未找到",

	4000: "请求失败",
	4001: "参数错误",
}

type Resp struct {
}

var webResp *Resp

func init() {
	webResp = new(Resp)
}

func (r *Resp) InvalidParametersError(c *gin.Context) {
	responseError(c, WRONG_PARAM, nil)
}

func (r *Resp) InternalServiceError(c *gin.Context, message ...string) {
	responseError(c, FAIL, message)
}

func (r *Resp) ResponseError(c *gin.Context, code int16, message ...string) {
	responseError(c, code, message)
}

func (r *Resp) ResponseSuccess(c *gin.Context, result any, msg ...string) {
	if msg == nil || len(msg) == 0 {
		msg = []string{WrongMessage[SUCCESS]}
	}
	responseOutput(c, SUCCESS, msg[0], result)
}

func responseOutput(c *gin.Context, code int16, message string, result any) {
	//if result == nil {
	//	result = ""
	//}
	c.JSON(http.StatusOK, ApiResponse{
		Code:    code,
		Message: message,
		Result:  result,
	})
	return
}

func responseError(c *gin.Context, code int16, message []string) {
	var msg string
	if len(message) == 0 || message[0] == "" {
		msg = WrongMessage[code]
	} else {
		msg = message[0]
	}
	responseOutput(c, code, msg, nil)
}
